// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package module

import (
	"context"
	"fmt"

	"github.com/kumose/kmopt/pkg/cluster/ctxt"
)

// ShellModuleConfig is the configurations used to initialize a KmoptModuleSystemd
type ShellModuleConfig struct {
	Command  string // the command to run
	Sudo     bool   // whether use root privilege to run the command
	Chdir    string // change working directory before running the command
	UseShell bool   // whether use shell to invoke the command
}

// ShellModule is the module used to control systemd units
type ShellModule struct {
	cmd  string // the built command
	sudo bool
}

// NewShellModule builds and returns a ShellModule object base on given config.
func NewShellModule(config ShellModuleConfig) *ShellModule {
	cmd := config.Command

	if config.Chdir != "" {
		cmd = fmt.Sprintf("cd %s && %s",
			config.Chdir, cmd)
	}

	if config.UseShell {
		cmd = fmt.Sprintf("%s -c '%s'",
			defaultShell, cmd)
	}

	return &ShellModule{
		cmd:  cmd,
		sudo: config.Sudo,
	}
}

// Execute passes the command to executor and returns its results, the executor
// should be already initialized.
func (mod *ShellModule) Execute(ctx context.Context, exec ctxt.Executor) ([]byte, []byte, error) {
	return exec.Execute(ctx, mod.cmd, mod.sudo)
}
